import { screenComprehensive } from '@/api/screen'

export default function useComprehensiveAnalysisOfKeyIndicators() {
  const lists = shallowRef<{ name: string, unit: string, data: number[] }[]>([])

  const title = ref('')
  const getComprehensiveAnalysisOfKeyIndicators = async () => {
    try {
      const { data } = await screenComprehensive()
      if (data) {
        lists.value = data.series || []
        title.value = data.name || ''
      }
    }
    catch (e) {
      console.warn(e)
    }
  }

  const active = ref('')
  const colors: [string, string][] = [
    ['rgba(19, 56, 144, 1)', 'rgba(109, 162, 239, 1)'],
    ['rgba(35, 84, 173, 1)', 'rgba(109, 163, 240, 1)'],
    ['rgba(26, 117, 155, 1)', 'rgba(58, 255, 248, 1)'],
    ['rgba(60, 178, 84, 1)', 'rgba(167, 240, 175, 1)'],
  ]
  const unit = ref('')
  const data = ref<number[]>([])
  const color = ref<[string, string]>(['rgba(19, 56, 144, 1)', 'rgba(109, 162, 239, 1)'])
  function switchButton(n: string, i: number) {
    active.value = n
    color.value = colors[i % colors.length]
    unit.value = lists.value[i].unit
    data.value = lists.value[i].data || []
  }

  let timer: ReturnType<typeof setInterval>
  function interval() {
    let i = unref(lists).findIndex(v => v.name === active.value)
    i = i === -1 ? 0 : i
    const d = unref(lists)

    if (d[0] && active.value === '') {
      switchButton(d[0].name, 0)
    }

    timer = setInterval(() => {
      if (d.length === 0)
        return
      const j = i % d.length
      const item = d[j]
      if (!item)
        return
      switchButton(item.name, j)
      i++
    }, 3e3)
  }

  function pause() {
    timer && clearInterval(timer)
  }
  function play() {
    interval()
  }

  onBeforeUnmount(() => {
    timer && clearInterval(timer)
  })

  return {
    lists,
    title,
    interval,
    active,
    unit,
    color,
    data,
    pause,
    play,
    switchButton,
    getComprehensiveAnalysisOfKeyIndicators,
  }
}
